package com.pig4cloud.pig.ads.controller.gdt;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dy.sdk.client.DyGdtClient;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.api.dto.OptimizationGoalDto;
import com.pig4cloud.pig.api.enums.GdtDeepWorthOptimizationGoalEnum;
import com.pig4cloud.pig.api.enums.GdtOptimizationGoalEnum;
import com.pig4cloud.pig.api.vo.OptimizationGoal;
import com.pig4cloud.pig.api.vo.OptimizationGoalVo;
import com.pig4cloud.pig.common.core.util.R;
import com.tencent.ads.model.DeepBehaviorOptimizationGoalPermissionStruct;
import com.tencent.ads.model.DeepWorthOptimizationGoalPermissionStruct;
import com.tencent.ads.model.OptimizationGoalPermissionsGetResponseData;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 优化目标
 * @Author chengang
 * @Date 2022/5/19
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/gdt/goal")
public class GdtOptimizationGoalController {

	private final GdtAccesstokenService gdtAccesstokenService;

	@PostMapping("/getOptimizationGoal")
	public R getOptimizationGoal(@RequestBody @Validated OptimizationGoalDto goalDto, BindingResult bindingResult) {
		try {
			if (bindingResult.hasErrors()) {
				return R.failed(bindingResult.getAllErrors().get(0).getDefaultMessage());
			}
			Long accountId = goalDto.getAccountId();
			DyGdtClient client = new DyGdtClient();
			Map<String, String> commonParams = gdtAccesstokenService.fetchAccesstoken(String.valueOf(accountId));
			if (commonParams == null || StringUtils.isEmpty(commonParams.get("access_token"))) {
				return R.failed("广点通ACCESSTOKEN失效,账号ID: "+ accountId);
			}
			String accessToken = commonParams.get("access_token");
//			List<String> siteSet = Lists.newArrayList("SITE_SET_MOBILE_UNION","SITE_SET_TENCENT_NEWS","SITE_SET_TENCENT_VIDEO");
			OptimizationGoalPermissionsGetResponseData response = client.getTencentAds(accessToken).optimizationGoalPermissions()
					.optimizationGoalPermissionsGet(accountId,
							goalDto.getSiteSet(),
							StringUtils.isBlank(goalDto.getPromotedObjectType())?"PROMOTED_OBJECT_TYPE_APP_ANDROID":goalDto.getPromotedObjectType(),
							goalDto.getBidMode(),
							goalDto.getPromotedObjectId(),
							null);
			List<OptimizationGoalVo> optimizationList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(response.getOptimizationGoalPermissionList())) {
				for(String optimizationGoal : response.getOptimizationGoalPermissionList()) {
					OptimizationGoalVo goalVo = new OptimizationGoalVo();
					// 设置优化目标
					goalVo.setValue(optimizationGoal);
					goalVo.setName(GdtOptimizationGoalEnum.valueByType(optimizationGoal));

					//设置深度优化目标行为目标组合
					List<OptimizationGoal> behaviorList = new ArrayList<>();
					if (CollectionUtils.isNotEmpty(response.getDeepBehaviorOptimizationGoalPermissionList())) {
						for (DeepBehaviorOptimizationGoalPermissionStruct behaviorStruct: response.getDeepBehaviorOptimizationGoalPermissionList()) {
							if (optimizationGoal.equals(behaviorStruct.getOptimizationGoal().getValue())) {
								for (String deepBehavior : behaviorStruct.getDeepBehaviorOptimizationGoalList()) {
									OptimizationGoal behavior = new OptimizationGoal();
									behavior.setValue(deepBehavior);
									behavior.setName(GdtOptimizationGoalEnum.valueByType(deepBehavior));
									behaviorList.add(behavior);
								}
							}
						}
					}
					goalVo.setBehaviorList(behaviorList);

					//设置深度优化 ROI 目标组合
					List<OptimizationGoal> worthList = new ArrayList<>();
					if (CollectionUtils.isNotEmpty(response.getDeepWorthOptimizationGoalPermissionList())) {
						for (DeepWorthOptimizationGoalPermissionStruct worthStruct: response.getDeepWorthOptimizationGoalPermissionList()) {
							if (optimizationGoal.equals(worthStruct.getOptimizationGoal().getValue())) {
								for (String deepWorth : worthStruct.getDeepWorthOptimizationGoalList()) {
									OptimizationGoal worth = new OptimizationGoal();
									worth.setValue(deepWorth);
									worth.setName(GdtDeepWorthOptimizationGoalEnum.getNameByType(deepWorth));
									worthList.add(worth);
								}
							}
						}
					}
					goalVo.setWorthList(worthList);

					optimizationList.add(goalVo);
				}
			}
			return R.ok(optimizationList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}

	@PostMapping("/getOptimizationGoal4Gdt")
	public R getOptimizationGoal4Gdt(@RequestBody @Validated OptimizationGoalDto goalDto, BindingResult bindingResult) {
		try {
			if (bindingResult.hasErrors()) {
				return R.failed(bindingResult.getAllErrors().get(0).getDefaultMessage());
			}
			Long accountId = goalDto.getAccountId();
			DyGdtClient client = new DyGdtClient();
			Map<String, String> commonParams = gdtAccesstokenService.fetchAccesstoken(String.valueOf(accountId));
			if (commonParams == null || StringUtils.isEmpty(commonParams.get("access_token"))) {
				return R.failed("广点通ACCESSTOKEN失效,账号ID: "+ accountId);
			}
			String accessToken = commonParams.get("access_token");
			OptimizationGoalPermissionsGetResponseData response = client.getTencentAds(accessToken).optimizationGoalPermissions()
					.optimizationGoalPermissionsGet(accountId,
							goalDto.getSiteSet(),
							StringUtils.isBlank(goalDto.getPromotedObjectType())?"PROMOTED_OBJECT_TYPE_APP_ANDROID":goalDto.getPromotedObjectType(),
							goalDto.getBidMode(),
							goalDto.getPromotedObjectId(),
							null);
			// OptimizationGoal 是枚举类，序列化会取name，故重新遍历
			// 使用getOptimizationGoal4接口
			return R.ok(response);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}
}
